﻿using System;
using System.Linq;
using System.Collections.Generic;

public class BullsAndCows
{
    private static string secret;

    static void Main()
    {
        PlayGame();
    }

    private static void PlayGame()
    {
        Console.WriteLine("Welcome to Bulls and Cows! There is a number generated for you\n" +
            "Please enter a number with 4 different digits.");
        bool finished = false;
        secret = GenerateSecret(4);
        while (finished == false)
        {
            string input = ReadNumber();
            Console.WriteLine(Respond(input, ref finished));
        }
        Console.WriteLine("Congratulations");
    }

    private static string GenerateSecret(int count)
    {
        if (count>10)
        {
            throw new ArgumentException("Unable to create a 10 non-repeating digit number.");
        }
        HashSet<int> digits = new HashSet<int>();
        Random generator = new Random();
        while (digits.Count != count)
        {
            digits.Add(generator.Next(0,10));
        }
        string result = string.Empty;
        foreach (var digit in digits)
        {
            result += digit;
        }
        return result;
    }

    private static string Respond(string input, ref bool finished)
    {
        int buls = GetBulls(input);
        int cows = GetCows(input);
        cows = cows - buls;
        if (buls == input.Length)
        {
            finished = true;
        }
        return string.Format("{0} BULLS and {1} COWS", buls, cows);
    }

    private static int GetCows(string input)
    {
        return input.Intersect(secret).Count();
    }

    private static int GetBulls(string input)
    {
        int bulls = 0;
        for (int i = 0; i < input.Length; i++)
        {
            if (secret[i] == input[i])
            {
                bulls++;
            }
        }
        return bulls;
    }

    private static string ReadNumber()
    {
        string input;
        while (true)
        {
            input = Console.ReadLine();
            if (input.Length != 4)
            {
                Console.WriteLine("4-digit number please!");
                continue;
            }
            if (!input.All((char x) => char.IsDigit(x)))
            {
                Console.WriteLine("This is not a number");
                continue;
            }

            HashSet<char> digits = new HashSet<char>(input);
            if (digits.Count!=4)
            {
                Console.WriteLine("There are repeating digits");
                continue;
            }
            return input;
        }        
    }
}